import axios from 'axios';
import qs from 'qs';

import history from '@src/utils/history';
import { serialize } from '@utils/utils';
import { getStore } from '@utils/store';

import errorCode from '@const/errorCode';

// import store from "@/store"; // progress bar style
axios.defaults.timeout = 300000;
// 返回其他状态吗
axios.defaults.validateStatus = function (status: number) {
    return status >= 200 && status <= 500; // 默认的
};
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration

// HTTPrequest拦截
axios.interceptors.request.use(
    (config: any) => {
        const TENANT_ID = getStore({ name: 'tenantId' });
        // const isToken = (config.headers || {}).isToken === false;
        // const token = store.getters.access_token;
        // if (token && !isToken) {
        //     config.headers["Authorization"] = "Bearer " + token; // token
        // }
        if (TENANT_ID) {
            config.headers['TENANT-ID'] = TENANT_ID; // 租户ID
        }

        // headers中配置serialize为true开启序列化
        if (config.method === 'post' && config.headers.serialize) {
            config.data = serialize(config.data);
            delete config.data.serialize;
        }

        if (config.method === 'get') {
            config.paramsSerializer = function (params: any) {
                return qs.stringify(params, { arrayFormat: 'repeat' });
            };
        }

        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    },
);

// HTTPresponse拦截
axios.interceptors.response.use(
    (res: any) => {
        console.log('axios-res', res);
        const status: number = Number(res.status) || 200;
        const statusCode: string = '';
        const message = res.data.msg || errorCode[statusCode] || errorCode['default'];
        if (status === 401) {
            // store.dispatch("FedLogOut").then(() => {
            //     router.push({ path: "/login" });
            // });
            return;
        }

        if (status !== 200 || res.data.code === 1) {
            // if (status === 400 || status === 500) {
            //     if (res.data.code === 0) {

            //     } else {

            //     }
            // } else {
            // }
            return Promise.reject(new Error(message));
        }

        // history.push('/blog');
        return res.data;
    },
    (error: any) => {
        return Promise.reject(new Error(error));
    },
);

export default axios;
